//
//  NumKeyboard.m
//  YunWu
//
//  Created by 古俊杰 on 16/10/8.
//  Copyright © 2016年 曲虹亮. All rights reserved.
//

#import "NumKeyboard.h"
#import "PhoneNumButton.h"
#import "UIView+Category.h"

@interface NumKeyboard()
{
    struct {
        unsigned int textInputSupportsShouldChangeTextInRange:1;
        unsigned int delegateSupportsTextFieldShouldChangeCharactersInRange:1;
        unsigned int delegateSupportsTextViewShouldChangeTextInRange:1;
    } _delegateFlags;
}
@property (weak, readwrite, nonatomic) UIResponder<UITextInput> *textInput;

@property (weak, nonatomic) IBOutlet PhoneNumButton *num_1_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_2_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_3_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_4_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_5_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_6_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_7_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_8_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_9_Button;
@property (weak, nonatomic) IBOutlet PhoneNumButton *num_0_Button;
//@property (weak, nonatomic) IBOutlet UIButton *num_clear_Button;

- (IBAction)btnClick:(UIButton *)sender;
@end

@implementation NumKeyboard

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self = [[NSBundle mainBundle] loadNibNamed:@"NumKeyboard" owner:nil options:nil][0];
        [self setupView];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupView
{
    _num_0_Button.tag = 0;
    
    _num_1_Button.tag = 1;
    
    _num_2_Button.tag = 2;
    _num_2_Button.phoneNumberText = @"ABC";
    
    _num_3_Button.tag = 3;
    _num_3_Button.phoneNumberText = @"DEF";
    
    _num_4_Button.tag = 4;
    _num_4_Button.phoneNumberText = @"GHI";
    
    _num_5_Button.tag = 5;
    _num_5_Button.phoneNumberText = @"JKL";
    
    _num_6_Button.tag = 6;
    _num_6_Button.phoneNumberText = @"MNO";
    
    _num_7_Button.tag = 7;
    _num_7_Button.phoneNumberText = @"PQRS";
    
    _num_8_Button.tag = 8;
    _num_8_Button.phoneNumberText = @"TUV";
    
    _num_9_Button.tag = 9;
    _num_9_Button.phoneNumberText = @"WXYZ";
    
//    _num_clear_Button.tag = 101;
    
    [self addNotificationsObservers];
}

//- (NSAttributedString *)getTitleAttributedString:(NSString *)title
//{
//    NSMutableAttributedString * attributedStr =[[NSMutableAttributedString alloc] initWithString:title];
//    NSRange range;
//    if (title.length > 6) {
//        range = NSMakeRange(3, title.length - 3);
//    } else {
//        range = NSMakeRange(2, title.length - 2);
//    }
//    NSLog(@"%lu",(unsigned long)title.length);
//    [attributedStr addAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} range:range];
//    return attributedStr;
//}

#pragma mark - 监听输入框事件

- (void)addNotificationsObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textDidBeginEditing:)
                                                 name:UITextFieldTextDidBeginEditingNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textDidBeginEditing:)
                                                 name:UITextViewTextDidBeginEditingNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textDidEndEditing:)
                                                 name:UITextFieldTextDidEndEditingNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textDidEndEditing:)
                                                 name:UITextViewTextDidEndEditingNotification
                                               object:nil];
}

- (void)textDidBeginEditing:(NSNotification *)notification {
    if (![notification.object conformsToProtocol:@protocol(UITextInput)]) {
        return;
    }
    
    UIResponder<UITextInput> *textInput = notification.object;
    
    if (textInput.inputAccessoryView && self == textInput.inputAccessoryView) {
        self.textInput = textInput;
        
        _delegateFlags.textInputSupportsShouldChangeTextInRange = NO;
        _delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange = NO;
        _delegateFlags.delegateSupportsTextViewShouldChangeTextInRange = NO;
        
        if ([self.textInput respondsToSelector:@selector(shouldChangeTextInRange:replacementText:)]) {
            _delegateFlags.textInputSupportsShouldChangeTextInRange = YES;
        } else if ([self.textInput isKindOfClass:[UITextField class]]) {
            id<UITextFieldDelegate> delegate = [(UITextField *)self.textInput delegate];
            if ([delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
                _delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange = YES;
            }
        } else if ([self.textInput isKindOfClass:[UITextView class]]) {
            id<UITextViewDelegate> delegate = [(UITextView *)self.textInput delegate];
            if ([delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) {
                _delegateFlags.delegateSupportsTextViewShouldChangeTextInRange = YES;
            }
        }
    }
}

- (void)textDidEndEditing:(NSNotification *)notification {
    self.textInput = nil;
}

#pragma mark - Additions

+ (NSRange)selectedRange:(id<UITextInput>)textInput {
    UITextRange *textRange = [textInput selectedTextRange];
    
    NSInteger startOffset = [textInput offsetFromPosition:textInput.beginningOfDocument toPosition:textRange.start];
    NSInteger endOffset = [textInput offsetFromPosition:textInput.beginningOfDocument toPosition:textRange.end];
    
    return NSMakeRange(startOffset, endOffset - startOffset);
}


#pragma mark - 按钮点击

- (IBAction)btnClick:(UIButton *)sender
{
    NSInteger tag = sender.tag;
    
    if (tag == 101) {
        [self clearButtonAction];
    }else{
        [self numberButtonAction:sender];
    }
    
}

-(void)setClickedDeleteBtn:(BOOL)clickedDeleteBtn
{
    _clickedDeleteBtn = clickedDeleteBtn;
    
     [self clearButtonAction];
}

- (void)numberButtonAction:(UIButton *)sender
{
    if (!isPad) {
        if (!self.textInput) {
            return;
        }
    }
    
    NSString *text;
    if ([sender.currentTitle componentsSeparatedByString:@"\n"].count > 0)
    {
        text = [sender.currentTitle componentsSeparatedByString:@"\n"][0];
        text = [text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];//去空格
    } else {
        text = sender.currentTitle;
    }
    
    if (isPad)
    {
        if ([self.delegate respondsToSelector:@selector(numKeyboardClicked:withKeyboardNumber:)]) {
            [self.delegate numKeyboardClicked:self withKeyboardNumber:text];
        }
        
    } else {
        if (_delegateFlags.textInputSupportsShouldChangeTextInRange) {
            if ([self.textInput shouldChangeTextInRange:self.textInput.selectedTextRange replacementText:text]) {
                [self.textInput insertText:text];
            }
        } else if (_delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange) {
            NSRange selectedRange = [[self class] selectedRange:self.textInput];
            UITextField *textField = (UITextField *)self.textInput;
            if ([textField.delegate textField:textField shouldChangeCharactersInRange:selectedRange replacementString:text]) {
                [self.textInput insertText:text];
            }
        } else if (_delegateFlags.delegateSupportsTextViewShouldChangeTextInRange) {
            NSRange selectedRange = [[self class] selectedRange:self.textInput];
            UITextView *textView = (UITextView *)self.textInput;
            if ([textView.delegate textView:textView shouldChangeTextInRange:selectedRange replacementText:text]) {
                [self.textInput insertText:text];
            }
        } else {
            [self.textInput insertText:text];
        }
    }
    
}

- (void)clearButtonAction {
    if (!self.textInput) {
        return;
    }
    
    if (_delegateFlags.textInputSupportsShouldChangeTextInRange) {
        UITextRange *textRange = self.textInput.selectedTextRange;
        if ([textRange.start isEqual:textRange.end]) {
            UITextPosition *newStart = [self.textInput positionFromPosition:textRange.start inDirection:UITextLayoutDirectionLeft offset:1];
            textRange = [self.textInput textRangeFromPosition:newStart toPosition:textRange.end];
        }
        if ([self.textInput shouldChangeTextInRange:textRange replacementText:@""]) {
            [self.textInput deleteBackward];
        }
    } else if (_delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange) {
        NSRange selectedRange = [[self class] selectedRange:self.textInput];
        if (selectedRange.length == 0 && selectedRange.location > 0) {
            selectedRange.location--;
            selectedRange.length = 1;
        }
        UITextField *textField = (UITextField *)self.textInput;
        if ([textField.delegate textField:textField shouldChangeCharactersInRange:selectedRange replacementString:@""]) {
            [self.textInput deleteBackward];
        }
    } else if (_delegateFlags.delegateSupportsTextViewShouldChangeTextInRange) {
        NSRange selectedRange = [[self class] selectedRange:self.textInput];
        if (selectedRange.length == 0 && selectedRange.location > 0) {
            selectedRange.location--;
            selectedRange.length = 1;
        }
        UITextView *textView = (UITextView *)self.textInput;
        if ([textView.delegate textView:textView shouldChangeTextInRange:selectedRange replacementText:@""]) {
            [self.textInput deleteBackward];
        }
    } else {
        [self.textInput deleteBackward];
    }
}

//#pragma mark - 点击联系人
//- (IBAction)contactClicked:(UIButton *)sender
//{
//    if ([_delegate respondsToSelector:@selector(NumKeyboardContactClicked:)]) {
//        [_delegate NumKeyboardContactClicked:self];
//    }
//}
//
//
//
//#pragma mark -- 拨打电话
//- (IBAction)phoneCallAction:(id)sender
//{
//    if ([_delegate respondsToSelector:@selector(NumKeyboardPhoneCallClicked:)]) {
//        [_delegate NumKeyboardPhoneCallClicked:self];
//    }
//}
//
//#pragma mark -- 隐藏拨号盘
//- (IBAction)hideView:(id)sender
//{
//    if ([_delegate respondsToSelector:@selector(NumKeyboardHideKeyboardClicked:)]) {
//        [_delegate NumKeyboardHideKeyboardClicked:self];
//    }
//}


@end
